/**
    MVP Tree data structure using graph database for I/O storage
    Copyright (C) 2014  David G. Starkweather

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

    David Starkweather starkd88@gmail.com
**/

package org.phash.mvptree;

import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.Direction;
import org.neo4j.graphdb.Transaction;
import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.Relationship;
import java.util.ArrayList;

abstract class MVPNode {

    static protected final String NODETYPE = "NODETYPEY";

    protected final Node node;
       
    public MVPNode(Node node){
	if (node == null)
	    throw new BadNodeException("null");

	this.node = node;
    }

    Node getNode(){

	return node;

    }


    void setAsTop(){
	Node node = getNode();
	Node refNode = node.getGraphDatabase().getReferenceNode();
	Transaction tx = node.getGraphDatabase().beginTx();;
	try {
	    refNode.createRelationshipTo(node, MVPRelationshipTypes.TO_TOP);
	    tx.success();
	} finally {
	    tx.finish();
	}
    }

    void deleteAsTop(){
	Node node = getNode();
	GraphDatabaseService graphdb = node.getGraphDatabase();
	Transaction tx = graphdb.beginTx();
	try {
	    Relationship rel = node.getSingleRelationship(MVPRelationshipTypes.TO_TOP, Direction.INCOMING);
	    rel.delete();
	    tx.success();
	} finally {
	    tx.finish();
	}
    }

    boolean isSameAs(MVPNode mvpNode){
	if (mvpNode != null && getNode().getId() == mvpNode.getNode().getId()){
	    return true;
	}
	return false;
    }

    void delete(){
	/* delete all relationships, (e.g. SV1 SV2 HAS )and underlying node */
	Node node = getNode();
	Transaction tx = node.getGraphDatabase().beginTx();
	try {
	    Iterable<Relationship> rels = node.getRelationships();
	    for (Relationship rel : rels){
		rel.delete();
	    }
	    node.delete();
	    tx.success();
	} finally {
	    tx.finish();
	}
    }
} 